import Honey from '../../utils/honey';

const app = getApp();
const honey = new Honey();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    user: {},
    chatList: [],
    scrollToId: [],
    content: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    wx.setStorageSync('isOpenChat', 'true');
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    const that = this;
    const user = honey.checkLogin('/pages/chat/index', false);
    that.setData({
      user: user
    })
    if (user) {
      that.getChatLog();
      setInterval(() => {
        that.getChatLog()
      }, 3000);
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
      wx.removeStorageSync('isOpenChat')
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  getChatLog: function() {
    const that = this;
    honey.post({
      alias: 'chatList',
      data: {
        user_id: that.data.user.id,
        token: that.data.user.token
      },
      success: function(res) {
        const chatList = res.data.data
        that.setData({
          chatList: chatList,
          scrollToId: that.getLastMsgId(chatList)
        })
      }
    })
  },
  getLastMsgId: function(list) {
    const length = list.length;
    if (length > 0) {
      return `msg${list[length - 1].id}`;
    }
    return '';
  },
  inputContent: function(e) {
    const that = this;
    const content = e.detail.value;
    that.setData({
      content: content
    })
  },
  sendMsg: function() {
    const that = this;
    honey.post({
      alias: 'addChat',
      data: {
        user_id: that.data.user.id,
        token: that.data.user.token,
        contents: that.data.content
      },
      success: function(res) {
        let msgModel = new Object();
        let chatList = that.data.chatList;
        msgModel.id = honey.randomString();
        msgModel.user_id = that.data.user.id;
        msgModel.type = 1;
        msgModel.contents = that.data.content;
        msgModel.headimg = that.data.user.headimg;
        chatList.push(msgModel);
        that.setData({
          chatList: chatList,
          scrollToId: that.getLastMsgId(chatList),
          content: ''
        })
      }
    })
  }
})